from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

# 1.获取数据
iris_data = load_iris()
# print(iris_data.target)
# print(iris_data.target_names)
# print(iris_data.data)
print(iris_data.feature_names)
# print(iris_data.DESCR)
# 2.数据分析和处理
# 2.1 数据可视化
# iris_df = pd.DataFrame(iris_data.data,columns=iris_data.feature_names)
# iris_df['label'] = iris_data.target
# # print(iris_df.head())
#
# sns.lmplot(x='petal width (cm)',y='sepal length (cm)',data=iris_df,hue='label',fit_reg=False)
# plt.show()

# 2.2 数据集划分
x_train, x_test, y_train, y_test = \
    train_test_split(iris_data.data, iris_data.target, test_size=0.2, random_state=22)
# print(len(iris_data.data))
# print(len(x_train))
# print(len(x_test))

# 3.特征工程-标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)

# 4.模型训练
knn = KNeighborsClassifier(n_neighbors=3)
# knn.fit(x_train, y_train)
#
# # 5.模型评估
# print(knn.score(x_test, y_test))
#
# # 6.模型预测
# new_data = [
#     [0.5, 1.2, 4.5, 5.2]
# ]
# new_data = transfer.transform(new_data)
# print(knn.predict(new_data))
# print(knn.predict_proba(new_data))

estimator =GridSearchCV(estimator=knn,param_grid={'n_neighbors':[3,5,7,9]},cv=4)
estimator.fit(x_train,y_train)

print(estimator.best_estimator_)
print(estimator.best_score_)
print(estimator.best_params_)
print(estimator.cv_results_)
print(estimator.score(x_test, y_test))

